const { ipcMain, BrowserWindow} = require('electron');
const path = require('path');

let child = null;

function createSubWin(mainWindow, isPackaged, url) {
  child = new BrowserWindow({
    width: 1000,
    height: 700,
    minWidth:1000,
    minHeight:700,
    parent: mainWindow,
    show: false,
    frame: false, //通过设置frame的值为false可以隐藏窗口的边框。
    titleBarStyle: 'hidden', // 显示最大化、最小化按钮
    titleBarOverlay: true,
    webPreferences: {
      preload: path.resolve(__dirname, './subPreload.js'),
    }
  });
  child.setWindowButtonVisibility(false)
  // 子窗口居中显示
  const parent_x = mainWindow.getPosition()[0];
  const parent_y = mainWindow.getPosition()[1];
  const parent_size_x = mainWindow.getSize()[0];
  const parent_size_y = mainWindow.getSize()[1];
  const settings_size_x = child.getSize()[0];
  const settings_size_y = child.getSize()[1];
  const settings_new_x = parent_x + (parent_size_x - settings_size_x) / 2;
  const settings_new_y = parent_y + (parent_size_y - settings_size_y) / 2;
  child.setPosition(
    parseInt(settings_new_x),
    parseInt(settings_new_y),
    false
  );
  //   加载窗口内容
  child.loadURL(url);
  child.show();
  if (!isPackaged) {
    child.webContents.openDevTools();
  }

  // 失去焦点关闭窗口
  child.on('blur', () => {
    if (isPackaged) {
      child.close();
    }
  });

  child.on('close', (e) => {
    // 阻止默认行为
    e.preventDefault();
    child.destroy();
  })

  // ipcMain
  ipcMain.handle('send-close-wind', () => {
    // child.close();
    child.destroy();
    // 清除主进程的监事件，避免控制台报错
    ipcMain.removeHandler('send-close-wind');
  })
}

// 创建一个子窗口
function openView(mainWindow,isPackaged) {
  ipcMain.handle('on-open-view', (e, url) => {
    if (child) {
      child.destroy();
      child = null;
    }
    createSubWin(mainWindow,isPackaged,url)
  });
}

module.exports = openView;
